package com.example.demo.controller;

import com.example.demo.custom.CustomResponse;
import com.example.demo.dto.LoginDto;
import com.example.demo.model.User;
import com.example.demo.model.UserLog;
import com.example.demo.service.Impl.UserLogServiceImpl;
import com.example.demo.service.Impl.UserServiceImpl;
import com.example.demo.service.IuserLogService;
import com.example.demo.service.IuserService;
import com.example.demo.utils.JwtUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;

@RestController
@AllArgsConstructor
public class AuthController {

    private final JwtUtils jwtUtils;

    private final IuserService iuserService;

    private final IuserLogService iuserLogService;

    @PostMapping("/login")
    @ResponseBody
    public CustomResponse login(@RequestBody LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();

        User user = iuserService.getUserByNamePass(username, password);

        // 这里简单模拟用户验证，实际应用中需要查询数据库进行验证
        if (user != null) {
            String token = jwtUtils.generateToken(user.getId().toString());
            UserLog userLog = new UserLog();
            userLog.setUserId(user.getId());
            userLog.setLoginType("LoginIn");
            userLog.setDate(LocalDateTime.now());
            iuserLogService.insertUserLog(userLog);
            return new CustomResponse("验证成功", token);
        } else {
            return new CustomResponse("用户名密码错误", "");
        }
    }

    @PostMapping("/logout")
    public CustomResponse logout(@RequestHeader("Authorization") String authorizationHeader) {
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            String key = jwtUtils.getInfoFromToken(token);
            jwtUtils.invalidateToken(key);
            Long id = Long.parseLong(key);
            UserLog userLog = new UserLog();
            userLog.setUserId(id);
            userLog.setLoginType("LoginOut");
            userLog.setDate(LocalDateTime.now());
            iuserLogService.insertUserLog(userLog);
//            String username = jwtUtils.getUsernameFromToken(token);
//            jwtUtils.deleteTokenFromRedis(username);
        }
        return new CustomResponse("注销成功");
    }
}